﻿/* ==============================================================================
 * 功能描述：MethodExtension  
 * 
 * 创 建 者：郑镇泉
 * 
 * 创建日期：2016/4/4 0:41:10
 * ==============================================================================*/
using UnityEngine;
using System.Collections;

namespace ZZQFrameWork
{
    public static class MethodExtension
    {
        public static T GetOrAddComponent<T>(this Transform transform, string path = "") where T : Component
        {
            Transform t;
            if (string.IsNullOrEmpty(path)) t = transform;
            else t = transform.Find(path);
            if (t == null)
            {
                Debug.LogError("not find T.transform,path:" + path);
                return null;
            }
            T ret = t.GetComponent<T>();
            if (ret == null)
                ret = t.gameObject.AddComponent<T>();
            return ret;
        }

        public static T GetOrAddComponent<T>(this GameObject gameObject, string path = "") where T : Component
        {
            return GetOrAddComponent<T>(gameObject.transform, path);
        }

        public static T GetComponentByPath<T>(this Transform transform,string path)where T:Component
        {
            Transform tr = null;
            tr = transform.Find(path);
            if (tr == null)
            {
                Debug.LogError("Not find transform,path:"+path);
                return null;
            }
            T t = tr.GetComponent<T>();
            if (t == null)
            {
                Debug.LogError("Not find T,path:" + path);
                return null;
            }
            return t;
        }

        public static T GetComponentByPath<T>(this GameObject gameObject , string path)
        {
            return GetComponentByPath<T>(gameObject,path);
        }
    }
}